<template>
    <view class="payment-edit-page">
      <!-- <view class="page-title">
        <text>编辑付款单</text>
      </view> -->
      
      <!-- 基本信息区域 -->
      <view class="info-section">
        <view class="info-item">
          <view class="info-icon"><u-icon name="account" size="20" color="#666666"></u-icon></view>
          <text class="info-label">供应商</text>
          <view class="info-value" @click="selectSupplier">{{ formData.supplierName || '请选择供应商' }}</view>
        </view>
      </view>
      
      <!-- 付款金额部分 -->
      <view class="payment-section">
        <view class="section-title">付款方式</view>
        <view class="payment-methods">
          <view class="payment-method-item">
            <text class="payment-method-name">现金</text>
            <input type="digit" class="payment-method-input" v-model="formData.cashAmount" 
              @input="updateTotalAmount" placeholder="0.00" />
          </view>
          <view class="payment-method-item">
            <text class="payment-method-name">银行存款</text>
            <input type="digit" class="payment-method-input" v-model="formData.bankAmount" 
              @input="updateTotalAmount" placeholder="0.00" />
          </view>
          <view class="payment-method-item">
            <text class="payment-method-name">微信</text>
            <input type="digit" class="payment-method-input" v-model="formData.wechatAmount" 
              @input="updateTotalAmount" placeholder="0.00" />
          </view>
          <view class="payment-method-item">
            <text class="payment-method-name">支付宝</text>
            <input type="digit" class="payment-method-input" v-model="formData.alipayAmount" 
              @input="updateTotalAmount" placeholder="0.00" />
          </view>
        </view>
        <view class="payment-total">
          <text class="payment-total-label">总金额</text>
          <text class="payment-total-value">{{ formatAmount(formData.totalAmount) }}</text>
        </view>
      </view>
      
      <!-- 备注区域 -->
      <view class="remark-section">
        <text class="remark-label">备注 (最多输入200个字)</text>
        <textarea class="remark-input" v-model="formData.remark" placeholder="请输入备注内容" maxlength="200"></textarea>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-bar">
        <button class="cancel-btn" @click="handleCancel">取消</button>
        <button class="save-btn" @click="handleSave">保存</button>
      </view>
      
      <!-- 供应商选择器 -->
      <u-picker :show="showSupplierPicker" :columns="[supplierColumns]" keyName="label" @confirm="confirmSupplier"
        @cancel="showSupplierPicker = false">
      </u-picker>
    </view>
  </template>
  
  <script>
  import api from '@/utils/api.js';
  
  export default {
    data() {
      return {
        id: null,
        type: null,
        formData: {
          supplierName: '',
          supplierId: null,
          totalAmount: 0,
          cashAmount: '',
          bankAmount: '',
          wechatAmount: '',
          alipayAmount: '',
          remark: ''
        },
        originalData: {}, // 保存原始数据，用于检测变化
        showSupplierPicker: false,
        supplierColumns: [],
        loading: false
      };
    },
    onLoad(options) {
      if (options.id) {
        this.id = options.id;
        this.type = options.type || 'paymentOrder';
        // 加载数据
        this.loadData();
        // 加载供应商列表
        this.loadSupplierList();
      } else {
        uni.showToast({
          title: '参数错误',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },
    methods: {
      // 加载付款单数据
      loadData() {
        uni.showLoading({ title: '加载中' });
        
        // 根据单据类型选择API
        let apiPromise;
        if (this.type === 'paymentOrder') {
          // 付款单
          apiPromise = api.getPurchaseDetail(this.id);
        } else {
          // 如果有其他类型的付款单，添加对应逻辑
          apiPromise = Promise.reject('不支持的单据类型');
        }
        
        apiPromise.then(res => {
          console.log('付款单数据:', res);
          
          if (res) {
            // 更新基本数据
            this.formData = {
              supplierId: res.supplierId,
              supplierName: res.supplierName || '',
              totalAmount: res.totalAmount || 0,
              cashAmount: res.cashAmount ? String(res.cashAmount) : '',
              bankAmount: res.bankAmount ? String(res.bankAmount) : '',
              wechatAmount: res.wechatAmount ? String(res.wechatAmount) : '',
              alipayAmount: res.alipayAmount ? String(res.alipayAmount) : '',
              remark: res.remark || ''
            };
            
            // 保存原始数据
            this.originalData = {...this.formData};
            
            // 如果有供应商ID但没有供应商名称，查询供应商信息
            if (res.supplierId && !res.supplierName) {
              this.loadSupplierName(res.supplierId);
            } else {
              uni.hideLoading();
            }
          } else {
            uni.hideLoading();
            uni.showToast({
              title: '获取数据失败',
              icon: 'none'
            });
          }
        }).catch(err => {
          uni.hideLoading();
          console.error('获取付款单数据失败:', err);
          uni.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
        });
      },
      
      // 加载供应商名称
      loadSupplierName(supplierId) {
        api.getSupplier(supplierId).then(supplierRes => {
          console.log('供应商信息:', supplierRes);
          
          // 更新供应商名称
          if (supplierRes && supplierRes.supplierName) {
            this.formData.supplierName = supplierRes.supplierName;
          }
          
          uni.hideLoading();
        }).catch(err => {
          console.error('获取供应商信息失败:', err);
          uni.hideLoading();
        });
      },
      
      // 加载供应商列表
      loadSupplierList() {
        api.listSupplier({ pageNum: 1, pageSize: 1000 }).then(res => {
          console.log('供应商列表:', res);
          
          if (res && res.rows && Array.isArray(res.rows)) {
            this.supplierColumns = res.rows.map(item => ({
              label: item.supplierName || '未命名供应商',
              value: item.supplierId
            }));
          }
        }).catch(err => {
          console.error('获取供应商列表失败:', err);
          uni.showToast({
            title: '获取供应商列表失败',
            icon: 'none'
          });
        });
      },
      
      // 格式化金额显示
      formatAmount(amount) {
        if (amount === undefined || amount === null) return '0.00';
        return parseFloat(amount).toFixed(2);
      },
      
      // 更新总金额
      updateTotalAmount() {
        // 将输入的金额转换为数字，确保非数字值为0
        const cashAmount = parseFloat(this.formData.cashAmount) || 0;
        const bankAmount = parseFloat(this.formData.bankAmount) || 0;
        const wechatAmount = parseFloat(this.formData.wechatAmount) || 0;
        const alipayAmount = parseFloat(this.formData.alipayAmount) || 0;
        
        // 计算总金额
        this.formData.totalAmount = Number((cashAmount + bankAmount + wechatAmount + alipayAmount).toFixed(2));
      },
      
      // 选择供应商
      selectSupplier() {
        if (this.supplierColumns.length === 0) {
          uni.showToast({
            title: '正在加载供应商列表',
            icon: 'none'
          });
          // 重新加载供应商列表
          this.loadSupplierList();
          return;
        }
        this.showSupplierPicker = true;
      },
      
      // 确认供应商选择
      confirmSupplier(e) {
        console.log('选择供应商:', e);
        
        if (e && e.value && e.value.length > 0) {
          const selectedItem = e.value[0];
          this.formData.supplierId = selectedItem.value;
          this.formData.supplierName = selectedItem.label;
        }
        
        this.showSupplierPicker = false;
      },
      
      // 取消编辑
      handleCancel() {
        uni.navigateBack();
      },
      
      // 保存付款单
      handleSave() {
        // 验证数据
        if (!this.formData.supplierId) {
          uni.showToast({
            title: '请选择供应商',
            icon: 'none'
          });
          return;
        }
        
        if (this.formData.totalAmount <= 0) {
          uni.showToast({
            title: '付款金额必须大于0',
            icon: 'none'
          });
          return;
        }
        
        // 构建提交数据
        const postData = {
          id: this.id,
          supplierId: this.formData.supplierId,
          supplierName: this.formData.supplierName,
          totalAmount: this.formData.totalAmount,
          cashAmount: parseFloat(this.formData.cashAmount) || 0,
          bankAmount: parseFloat(this.formData.bankAmount) || 0,
          wechatAmount: parseFloat(this.formData.wechatAmount) || 0,
          alipayAmount: parseFloat(this.formData.alipayAmount) || 0,
          remark: this.formData.remark,
          type: this.type
        };
        
        console.log('提交数据:', postData);
        uni.showLoading({ title: '保存中' });
        
        // 调用更新API
        let apiPromise;
        if (this.type === 'paymentOrder') {
          // 更新付款单
          apiPromise = api.updatePurchase(postData);
        } else {
          // 如果有其他类型的付款单，添加对应逻辑
          apiPromise = Promise.reject('不支持的单据类型');
        }
        
        apiPromise.then(res => {
          uni.hideLoading();
          
          if (res && res.code === 200) {
            uni.showToast({
              title: '保存成功',
              icon: 'success'
            });
            
            // 返回详情页
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            uni.showToast({
              title: res?.msg || '保存失败',
              icon: 'none'
            });
          }
        }).catch(err => {
          uni.hideLoading();
          console.error('保存付款单失败:', err);
          uni.showToast({
            title: '保存失败',
            icon: 'none'
          });
        });
      }
    }
  };
  </script>
  
  <style lang="scss" scoped>
  .payment-edit-page {
    min-height: 100vh;
    background-color: #f5f7fa;
    padding-bottom: 120rpx;
  }
  
  .page-title {
    background-color: #4A8CFF; // 使用蓝色区分付款单
    padding: 30rpx;
    text-align: center;
    
    text {
      color: #fff;
      font-size: 32rpx;
      font-weight: 500;
    }
  }
  
  // 基本信息区域
  .info-section {
    background-color: #ffffff;
    margin-top: 20rpx;
    
    .info-item {
      display: flex;
      align-items: center;
      padding: 25rpx 30rpx;
      
      .info-icon {
        margin-right: 15rpx;
      }
      
      .info-label {
        font-size: 28rpx;
        color: #333333;
        width: 100rpx;
      }
      
      .info-value {
        flex: 1;
        font-size: 28rpx;
        color: #666666;
        text-align: right;
      }
    }
  }
  
  // 付款方式区域
  .payment-section {
    background-color: #ffffff;
    margin-top: 20rpx;
    
    .section-title {
      font-size: 28rpx;
      color: #333333;
      font-weight: 500;
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
    }
  }
  
  .payment-methods {
    display: flex;
    flex-direction: column;
    padding: 10rpx 30rpx;
    
    .payment-method-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      .payment-method-name {
        font-size: 28rpx;
        color: #333333;
      }
      
      .payment-method-input {
        width: 200rpx;
        text-align: right;
        font-size: 28rpx;
        color: #666666;
        padding: 5rpx;
      }
    }
  }
  
  .payment-total {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    border-top: 1rpx solid #f0f0f0;
    
    .payment-total-label {
      font-size: 28rpx;
      color: #333333;
      font-weight: 500;
    }
    
    .payment-total-value {
      font-size: 32rpx;
      color: #4A8CFF; // 使用蓝色区分付款单
      font-weight: bold;
    }
  }
  
  // 备注区域
  .remark-section {
    background-color: #ffffff;
    margin-top: 20rpx;
    padding: 20rpx 30rpx;
    
    .remark-label {
      font-size: 28rpx;
      color: #333333;
      margin-bottom: 15rpx;
      display: block;
    }
    
    .remark-input {
      width: 100%;
      height: 150rpx;
      background-color: #f5f5f5;
      border-radius: 8rpx;
      padding: 15rpx;
      font-size: 28rpx;
      color: #333333;
    }
  }
  
  // 底部操作栏
  .action-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    background-color: #ffffff;
    padding: 20rpx 30rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .cancel-btn, .save-btn {
      flex: 1;
      height: 80rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 28rpx;
      border-radius: 12rpx;
      margin: 0 10rpx;
    }
    
    .cancel-btn {
      background-color: #ffffff;
      color: #666666;
      border: 1rpx solid #e0e0e0;
    }
    
    .save-btn {
      background-color: #4A8CFF; // 使用蓝色区分付款单
      color: #ffffff;
      border: none;
    }
  }
  </style> 